package com.bosch.in.rtp1.ept.manager.impl;

import java.sql.SQLException;
import java.util.List;

import com.bosch.in.rtp1.ept.dao.RelHldDiagramDao;
import com.bosch.in.rtp1.ept.manager.RelHldDiagramManager;
import com.bosch.in.rtp1.ept.model.dto.RelHldChartFactor;
import com.bosch.in.rtp1.ept.model.technical.Condition4RelHldDiagram;
import com.bosch.in.rtp1.ept.util.DaoFactory;
import com.bosch.in.rtp1.ept.util.ehcache.EhcacheFactory;


public class RelHldDiagramManagerImpl implements RelHldDiagramManager {

	/**
	 * used to manage connection
	 */
	private DBConnectionManager dbManager;
	/**
	 * DAO object to get Released hold data.
	 */
	private RelHldDiagramDao relHldDiagramDao;
	
	/**
	 * Look up datasource to get connection from pre-initialized connection pool
	 * @throws Exception
	 */
	public RelHldDiagramManagerImpl() { 
	}

	@Override
	public List<RelHldChartFactor> getFactorList(
			Condition4RelHldDiagram condition4RelHldDiagram)
			throws SQLException {
		try
		{
			return this.getRelHldChartFactor(condition4RelHldDiagram);
		}
		finally
		{
			if (dbManager != null) {
				dbManager.close();
			}
		}
	}
	
	/***********PRIVATE METHOD****************/
	
	/**
	 * lazy initialize connection when we really need to interact with database and in case 
	 * data can't be found in caching system.
	 * @throws SQLException
	 */
	private void init() throws SQLException {
		dbManager = new DBConnectionManager();
		relHldDiagramDao = DaoFactory.getInstance().getRelHldDiagramDao(dbManager.getConnection());
	}
	
	/**
	 * Try to load the list of RelHldChartFactor from cache first. 
	 * If it is not found, try loading from database
	 * @param Condition4RelHldDiagram
	 * @return List<RelHldChartFactor>
	 * @throws SQLException
	 */
	private List<RelHldChartFactor> getRelHldChartFactor(Condition4RelHldDiagram condition4RelHldDiagram) throws SQLException
	{
		// try to load eqpType list from cache	
		List<RelHldChartFactor> chartFactors = EhcacheFactory.getRelHldDiagramcacheWrapper().get(condition4RelHldDiagram.getParameterValues().toString());
		if (chartFactors == null)
			{
				// lazy init connection
				init();
				// load chartFactors list from database if it is not in cache  
				chartFactors = relHldDiagramDao.getFactorList(condition4RelHldDiagram);
				//put chartFactors list into cache
				if (chartFactors.size()>0)
				{
					EhcacheFactory.getRelHldDiagramcacheWrapper().put(condition4RelHldDiagram.getParameterValues().toString(), chartFactors);
				}
			}
		return chartFactors;
	}

}
